const express = require('express')
const router = express.Router()
const db = require('../utils/db')
const { md5 } = require('utility')
const jwt = require('jsonwebtoken')




//注册
router.post('/api/reguser', (req, res) => {
    const { username, password } = req.body
    let newPassword = md5(password)
    db(`INSERT INTO user SET username='${username}',password='${newPassword}'`, (err, result) => {
        if (err) return res.send({ status: 1, message: '注册失败，请检查用户名或密码！' })
        res.send({ status: 0, message: '注册成功！' })
    })
})



//登录
router.post('/api/login', (req, res) => {
    const { username, password } = req.body
    let newPassword = md5(password)
    db(`SELECT * from user WHERE username='${username}' AND password='${newPassword}'`, (err, result) => {
        let token = jwt.sign({ id: result[0].id }, 'haha', { expiresIn: '24h' })
        if (err || result.length === 0) return res.send({ status: 1, message: '登录失败！' })
        res.send({ status: 0, message: '登录成功！', token: 'Bearer ' + token })
    })
})




// 获取用户的基本信息
router.get('/my/userinfo', (req, res) => {
    const { id } = req.user
    db(`SELECT id,username,nickname,email,user_pic FROM user WHERE id=${id}`, (err, result) => {
        if (err || result.length === 0) return res.send({ status: 1, message: '获取失败' })
        res.send({ status: 0, message: '获取用户基本信息成功！', data: result[0] })
    })
})



//更新用户的基本信息
router.post('/my/userinfo', (req, res) => {
    const { id } = req.user
    const { nickname, email } = req.body
    db(`UPDATE user SET nickname='${nickname}',email='${email}' WHERE id = ${id}`, (err, result) => {
        if (err || result.changedRows === 0) return res.send({ status: 1, message: '修改失败' })
        res.send({ status: 0, message: '修改用户信息成功！' })
    })
})



//重置密码
router.post('/my/updatepwd', (req, res) => {
    const { id } = req.user
    const { oldPwd, newPwd } = req.body
    let oldPassword = md5(oldPwd)
    let newPassword = md5(newPwd)
    db(`UPDATE user SET password='${newPassword}' WHERE id = ${id}`, (err, result) => {
        if (err || result.changedRows === 0) return res.send({ status: 1, message: '更新密码失败' })
        res.send({ status: 0, message: '更新密码成功！' })
    })
})


// 更换头像
router.post('/my/update/avatar', (req, res) => {
    const { id } = req.user
    const { avatar } = req.body
    console.log({ id, avatar })
    db(`UPDATE user SET user_pic='${avatar}' WHERE id = ${id}`, (err, result) => {
        console.log(result)
        if (err || result.changedRows === 0) return res.send({ status: 1, message: '更新头像失败' })
        res.send({ status: 0, message: '更新头像成功！' })
    })
})









module.exports = router